<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\Device;
use App\Model\Normal;
use App\Model\Order;
use Hyperf\AsyncQueue\Job;

class CheckPaid extends Job
{
    public string $orderNum;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 0;


    public function __construct($orderNum)
    {
        // 这里最好是普通数据，不要使用携带 IO 的对象，比如 PDO 对象
        $this->orderNum = $orderNum;
    }

    public function handle()
    {
        $orderModel = Order::where('number', $this->orderNum)->where('status',Order::STATUS_PAID)->first();
        try{
            if($orderModel) {
                $device  = Device::query()->where('id',$orderModel->device_id)
                    ->first();
                $portStatus = json_decode($device->port_status,true);
                if(isset($portStatus[$orderModel->channel_number])){
                    if($portStatus[$orderModel->channel_number]['status'] == 2){
                        $orderModel->status = Order::STATUS_USING;
                        $orderModel->save();
                    }
                }else{
                    $orderModel->fail('订单超时异常',true);
                }
            }
        }catch (\Exception $e){
             Normal::logger('设备开启' . $this->orderNum . '异常--'.$e->getMessage(), 'order-queue', 'error');
        }
    }
}
